import base64
import binascii
import json
import re

import requests
import rsa

head = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'Origin': 'http://weibo.com',
        "Referer": "http://weibo.com/",
        'User-Agent': 'Mozilla/5.0(Windows NT 6.1;WOW64;Trident/7.0;rv:11.0)like Gecko',
        'Host': 'login.sina.com.cn'}

data = {
    "entry": "weibo",
    "gateway": "1",
    "savestate": "7",
    "useticket": "1",
    "pagerefer": "https://m.weibo.cn/p/102803_ctg1_8999_-_ctg1_8999_home",
    "vsnf": "1",
    "su": "",
    "service": "miniblog",
    "servicetime": "",
    "nonce": "",
    "pwencode": "rsa2",
    "rsakv": "",
    "sp": "",
    "sr": "1366*768",
    "encoding": "UTF-8",
    "prelt": "76",
    "url": "https://m.weibo.cn/p/102803_ctg1_8999_-_ctg1_8999_home",
    "returntype": "META"
}


def login(email='18101038354', password='qingdian123'):
    pre_url = "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=emhlZGFwYXQlNDAxNjMuY29t&rsakt=mod&client=ssologi"
    s = requests.session()
    res = s.get(pre_url)
    res = res.text.split('(')[-1].split(')')[0]
    pre_json = json.loads(res)
    servertime = pre_json['servertime']
    nonce = pre_json['nonce']
    rsakv = pre_json['rsakv']
    pubkey = pre_json['pubkey']
    # urllib.quote()是进行url编码
    # su是经过一次base64加密之后的账号
    su = base64.b64encode(bytes(email, encoding='utf-8'))
    # rsa2计算sp
    rsaPubkey = int(pubkey, 16)
    key = rsa.PublicKey(rsaPubkey, 65537)
    message = str(servertime) + '\t' + str(nonce) + '\n' + str(password)
    sp = rsa.encrypt(message.encode('utf-8'), key)
    sp = binascii.b2a_hex(sp)
    data['servertime'] = servertime
    data['nonce'] = nonce
    data['rsakv'] = rsakv
    data['su'] = su
    data['sp'] = sp
    #
    post_url = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)&wsseretry=servertime_error"
    res = s.post(post_url, data=data).text
    p = re.compile('location\.replace\(\'(.*?)\'\)')
    final_url = p.search(res).group(1)
    res = s.get(final_url)
    uidRe = re.compile('uid: \'(\d*)\'')
    cookie_str=''
    _T_WM=''
    SUB=''
    req = {}
    for i in s.cookies:
        cookie_str +=' '+i.name+':'+i.value+';'
        if i.name == 'SUB':
            req['SUB'] = i.value
            SUB=i.value
        if i.name =='_T_WM':
            _T_WM=i.value
        cookie_str=f'_T_WM={_T_WM}; SUB={SUB}'
    return req,cookie_str
if __name__ == '__main__':
    print(login('18101038354', 'qingdian123'))
